package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"home-info-site/models/cache"
	"home-info-site/models/mysql"
	"time"

	"home-info-site/userrpc/internal/svc"
	"home-info-site/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询
func (l *ProductListLogic) ProductList(in *userrpc.ProductListRequest) (*userrpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line

	var list []*userrpc.ProductList
	var user mysql.User
	if err := user.FindUserByUserId(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}
	key := fmt.Sprintf("list_%s", in)
	cacheData, _ := cache.Rdb.Get(l.ctx, key).Result()
	if cacheData == "" {
		list = mysql.ProductList(mysql.DB, list, in.UserId)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, key, jsonData, time.Minute*20)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	return &userrpc.ProductListResponse{
		List: list,
	}, nil
}
